<?php

namespace App\Console\Commands;

use App\Common\Curl;
use App\Models\V1\LiveModel;
use Illuminate\Console\Command;

class PushViews extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'push:views';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'tell you now live times';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('Display this on the screen');
        $live = LiveModel::where(['is_show' => 1, 'is_end' => 0])->orderBy('id', 'desc')->first();
        $url  = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
        $url  = $this->InitTim($url);
        $this->info($url);

//        $curl = new Curl();

        $params = [
            'GroupId' => $live->chat_group_id,
            'Name'    => $live->viewed_times
        ];
        $this->info(json_encode($params));
//        $data = $curl->Post($url, $params);
        $data = $this->curl_json($url, $params);
        $this->info($data);
    }

    //初始格式api
    public function InitTim($url = '')
    {
        $live             = config('live');
        $sdkappid         = $live['SdkAppId'];
        $identifier       = $live['Identifier'];
        $private_pem_path = $live['PrivateKeyPath'];
        $signature        = $live['Signature'];
        $contenttype      = 'json';
        $random           = 9999999;

        $usersig = $this->signature($signature, $private_pem_path, $sdkappid, $identifier);

        $params = [
            'usersig'     => $usersig,
            'identifier'  => $identifier,
            'sdkappid'    => $sdkappid,
            'random'      => $random,
            'contenttype' => $contenttype
        ];
        $url    = $url . http_build_query($params);

        return $url;
    }

    //签名
    public function signature($signature, $private_pem_path, $sdkappid, $identifier)
    {
        $file    = app_path('../zhengshu/tencent/sig');
        $command = $signature
            . ' ' . 'gen'
            . ' ' . escapeshellarg($private_pem_path)
            . ' ' . $file
            . ' ' . escapeshellarg($sdkappid)
            . ' ' . escapeshellarg($identifier);

        $ret = exec($command, $out, $status);
        if ($status == -1) {
            return null;
        }
        $sig = file_get_contents(app_path('../zhengshu/tencent/sig'));

        return $sig;
    }

    protected function curl_json($url, array $params)
    {
        $curl = new Curl();
        $data = $curl->PostJson($url, json_encode($params));

        return json_decode($data, true);
    }
}
